<?php
//(c) Copyright 2016 wonyun. All Rights Reserved.
/**
 *
 * 配送员订单管理模块
 * author：Rogermmg
 **/
class DeliveryAction extends Action {
    public function _initialize(){
		$action = array(
			'users'=>array('li','upload'),
			'anonymous'=>array('')
		);
		B('Authenticate', $action);
	}
	
	//清理缓存
	public function cacheclear(){
		F('user',NULL);
		alert('success', '缓存清理成功！', U('chrm/delivery/li'));
	}
	
	//生成用户团队
	public function user_team(){
		$d_delivery=D("Delivery");
		
		
	}
	
	//详情单列表
	public function li(){
        $d_mongo = D("Mongo");
        $d_delivery=D("Delivery");
        $dtime=array(
        	"start"=>date("Y-m-d",strtotime("-1 month ")),
        	"end"=>date("Y-m-d")
        );

        $where['t_start'] = $this -> _get('t_start', 'trim', '');
        $where['t_end'] = $this -> _get('t_end', 'trim', '');
        $where['teamid'] = json_decode($this -> _get('teamid', 'trim', ''), TRUE);

        $sort = array("city" => 1, "ordered" => -1);
        $p = $this -> _get('p', 'intval', 1);

        if ($where['t_start']) {
            //选择时间区间
            $teamtime=array(
                't_start'=>$where['t_start'],
                't_end'=>$where['t_end']
            );
            /*$status = $where;
            $status['teamid']=urlencode(json_encode($where['teamid']));*/

            //改变数组中字符串为整形
            foreach($where['teamid'] as $k=>$tid){
                $teamid[$k]=(int)$tid;
            }

            if (!$where['teamid']) {
                $lwhere = array("docid" => array("\$gt" => strtotime($where['t_start']), "\$lte" => strtotime($where['t_end'])));
            } else {
//              $lwhere = array("docid" => array("\$gt" => strtotime($where['t_start']), "\$lte" => strtotime($where['t_end'])), "teamid" => array('$in'=>array_values($teamid)));
				$lwhere = array("docid" => array("\$gt" => strtotime($where['t_start']), "\$lte" => strtotime($where['t_end'])), "teamid" => $teamid);
            }
        }else{
//                  $lwhere = '';
			$lwhere = array("docid" => array("\$gt" => strtotime($dtime['start']), "\$lte" => strtotime($dtime['end'])));
        }
        //$olist = $d_mongo -> Pagefind($lwhere, $p, $status, $sort, 50,'delivery_detail');
		
		$teamset=M("delivery_team")->select();
		
        $olist = $d_delivery->page_user($lwhere, $p);
        
//          dump($teamid);exit;
       
        $this -> assign('olist', $olist['userlist']);
        $this -> assign('page', $olist['page']);
        $this -> assign('teamid', $teamid);
        $this -> assign('teamset', $teamset);
        $this -> assign('dtime', $dtime);
        $this -> assign('teamtime', $teamtime);
        $this->alert = parseAlert();
        $this->display();
	}
	
	//团队工资公式列表
	public function team_set(){
		$team=D("Delivery")->teamlist();
		$this -> assign('team', $team);
        $this->alert = parseAlert();
        $this->display();																																																																																																	
	}
	//设置公式
	public function setwage(){
		header('Content-Type:text/html; charset=utf-8');
		if($_GET['tid']){
			$teamone=D("Delivery")->tidedit($_GET['tid']);
			

			$this -> assign('team', $teamone);
			$this->display();
		}else{
			alert('error', '非法操作！', U('chrm/delivery/team_set'));
		}
	}
	public function wage_edit(){
		if(IS_POST and $_POST['tid']!=''){
			$formula=array(
				'work'=>$_POST['work'],
				'normal'=>$_POST['normal'],
				'outtime'=>$_POST['outtime'],
				'qizha'=>$_POST['qizha'],
			);
			$data['formula']=json_encode($formula);
			$data['edit_user']=$_SESSION['user_id'];
			$update=M("delivery_team")->where(array("id"=>$_POST['tid']))->save($data);
			if($update){
				alert('success', '设置成功！', U('chrm/delivery/team_set'));
			}
		}else{
			alert('error', '非法操作！', U('chrm/delivery/team_set'));
		}
	}
	
	//导出指定日期工资单
	public function wage(){}
	

	
	//考核表
	public function assess(){}
	
	//导入配送员详单
	public function upload(){
//		set_time_limit(0); 
		if ($this -> isPost()) {
			$m_mongo = M('mongo');
			$m_dep=M("department");
			$d_mongo = D("Mongo");
			$d_delivery=D("Delivery");
			
			$times=time();
			if (isset($_FILES['excel']['size']) && $_FILES['excel']['size'] != null) {
				import('@.ORG.UploadFile');
				$upload = new UploadFile();
				$upload -> maxSize = 20000000;
				$upload -> allowExts = array('xls', 'xlsx');
				$dirname = './Uploads/excel/' . date('Ym', time()) . '/' . date('d', time()) . '/';
				if (!is_dir($dirname) && !mkdir($dirname, 0777, true)) {
					alert('error', '附件上传目录不可写', U('chrm/delivery/upload'));
				}
				$upload -> savePath = $dirname;
				if (!$upload -> upload()) {
					alert('error', $upload -> getErrorMsg(), U('chrm/delivery/upload'));
				} else {
					$info = $upload -> getUploadFileInfo();
				}
			}
			//dump($_FILES);exit();
			if (is_array($info[0]) && !empty($info[0])) {
				$savePath = $dirname . $info[0]['savename'];
			} else {
				alert('error', '上传失败', U('chrm/delivery/upload'));
			}
			import("ORG.PHPExcel.PHPExcel");
			$PHPExcel = new PHPExcel();
			$PHPReader = new PHPExcel_Reader_Excel2007();
			if (!$PHPReader -> canRead($savePath)) {
				$PHPReader = new PHPExcel_Reader_Excel5();
			}
			$PHPExcel = $PHPReader -> load($savePath);
			$currentSheet = $PHPExcel -> getSheet(0);
			$allRow = $currentSheet -> getHighestRow();
			if ($allRow <= 1) {
				alert('error', '上传文件无有效数据', U('chrm/delivery/li'));
			} else {

				for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
					$adddate=$currentSheet -> getCell('A' . $currentRow) -> getValue();
					
					//$Docid=intval(PHPExcel_Shared_Date::ExcelToPHP($psid));
					$Docid=intval(($adddate - 25569) * 3600 * 24);
					$psid=date("Y-m-d",$Docid);
					$tname=$currentSheet -> getCell('B' . $currentRow) -> getValue();
					$tname=str_replace("可用可信","",$tname);
					$tname=str_replace(' ','',$tname);
					$data=array(
						"wid"=>$times,
						"docid"=>$Docid,
						"adddate"=>$psid,
						"psname"=>$currentSheet -> getCell('F' . $currentRow) -> getValue(),
						"teamname"=>$tname,
						"comname"=>$currentSheet -> getCell('C' . $currentRow) -> getValue(),
						"ordercome"=>$currentSheet -> getCell('D' . $currentRow) -> getValue(),
						"ordernum"=>trim($currentSheet -> getCell('E' . $currentRow) -> getValue()),
						
					);
					$status_d=$currentSheet -> getCell('G' . $currentRow) -> getValue();
					switch($status_d){
						case "正常":
							$data['status']=1;
							break;
						case "超时":
							$data['status']=2;
							break;
						case "疑似欺诈":
							$data['status']=0;
							break;
						case "异常":
							$data['status']=3;
							break;
					}
					$data['vio']=$currentSheet -> getCell('H' . $currentRow) -> getValue();
					if($data['vio']=="是"){
						$data['vio']=1;
					}else{
						$data['vio']=0;
					}
					$data['base']=$currentSheet -> getCell('I' . $currentRow) -> getValue();
					$data['tidian']=$currentSheet -> getCell('J' . $currentRow) -> getValue();
					$data['bt_hd']=$currentSheet -> getCell('K' . $currentRow) -> getValue();
					$data['bt_dj']=$currentSheet -> getCell('L' . $currentRow) -> getValue();
					$data['bt_sx']=$currentSheet -> getCell('M' . $currentRow) -> getValue();
					$data['sx_kk']=$currentSheet -> getCell('N' . $currentRow) -> getValue();
					$data['ddcs']=$currentSheet -> getCell('O' . $currentRow) -> getValue();
					$data['yckk']=$currentSheet -> getCell('P' . $currentRow) -> getValue();
					$data['value']=$data['base']+$data['tidian']+$data['bt_hd']+$data['bt_dj']+$data['bt_sx']+$data['bt_kk']+$data['ddcs']+$data['yckk'];
//					$data['delivery_user']=$d_delivery->contuser($data['psname'],$tname);//添加用户系统用户关联
//					$data['delivery_team']=$d_delivery->conteam($tname);//添加团队系统用户关联
					if(!$data["docid"]){
						$d_mongo ->remove(array("docid"=>$data["docid"]),'delivery_detail');
						alert('error', '上传文件数据格式不正确！', U('chrm/delivery/li'));
					}

					$adddata = $d_mongo -> add($data,'delivery_detail');
					if (!$adddata) {
						alert('error', '出错=》' . $adddata, U('chrm/delivery/li'));
						break;
					}
					
					//用户检索
					$cha=$d_delivery->arr2($data['psname'],$psname);
					if(!$cha){
						$psname[]=array(
							'psname'=>$data['psname'],
							'teamname'=>$tname
						);
					}
					
				}
				
				$m_mongos = array();
				$m_mongos['type']='order';
				$m_mongos['oldname']=$_FILES['excel']["name"];
				$m_mongos['filename'] = $info[0]['savename'];
				$m_mongos['fileid'] = $Docid;
				$m_mongos['wid']=$times;
				$m_mongos['user_id'] = $_SESSION['user_id'];
				$m_mongos['update'] = time();
				if (!$m_mongo -> data($m_mongos) -> add()) {
					alert('error', '出错=》MYSQL写入失败', U('chrm/delivery/li'));
				}
				
				//用户写入
				foreach($psname as $vo){
					$finduser=M('delivery_user')->where(array("nickname"=>$vo['psname']))->find();
					if(!$finduser){
						$udata['nickname']=$vo['psname'];
						$udata['teamid']=$d_delivery->conteam($vo['teamname']);
						$udata['update']=$times;
//						dump($udata);exit;
						M('delivery_user')->add($udata);
					}elseif(empty($finduser['teamid']) or $finduser['teamid']==0){
						$udata['teamid']=$d_delivery->conteam($vo['teamname']);
						$udata['update']=$times;
						M('delivery_user')->where(array('id'=>$finduser['id']))->save($udata);
					}
				}
				alert('success', '导入成功！', U('chrm/delivery/li'));
			}
		}else{
			$this -> alert = parseAlert();
			$this -> display();
		}
	}
	
	
}

?>